<?php

namespace app\admin\model;

use ba\Random;
use think\Model;

/**
 * Staff
 */
class Staff extends Model
{
    // 表名
    protected $name = 'staff';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'device',
        'department',
    ];


    public function getDeviceAttr($value, $row): array
    {
        return [
            'name' => \app\admin\model\Device::whereIn('id', $row['device_ids'])->column('name'),
        ];
    }

    public function getDeviceIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setDeviceIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getDepartmentAttr($value, $row): array
    {
        return [
            'name' => \app\admin\model\Department::whereIn('id', $row['department_ids'])->column('name'),
        ];
    }

    public function getDepartmentIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setDepartmentIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\User::class, 'user_id', 'id');
    }

    public static function onAfterInsert(Model $model): void
    {
        $salt   = Random::build('alnum', 16);
        $passwd = encrypt_password('123456', $salt);
        $time = time();
        $user = [
            'group_id' => 999,
            'username'=> $model->phone,
            'nickname'=> $model->getData('name'),
            'mobile'=> $model->phone,
            'password'=> $passwd,
            'salt'=> $salt,
            'createtime'=> $time,
            'updatetime'=> $time,
            'status'=> 'enable'
        ];
        $user_model = \app\common\model\User::create($user);
        $model->user_id = $user_model->id;
        $model->save();
    }

    public static function onAfterDelete(Model $model): void
    {
        \app\common\model\User::destroy($model->user_id);
    }
}